<?php

namespace app\interfaces\controller;



use app\interfaces\model\Member as MemberModel;

use app\interfaces\model\MemberCoupon as MemberCouponModel;

use app\interfaces\model\MemberPacket as MemberPacketModel;

use app\interfaces\model\MemberBrokerage as MemberBrokerageModel;

use app\interfaces\model\MemberDistribution as MemberDistributionModel;

use app\interfaces\model\MemberGrade as MemberGradeModel;

use app\interfaces\model\MemberCollect as MemberCollectModel;

use app\interfaces\model\MemberBrowse as MemberBrowseModel;

use app\interfaces\model\MemberOrder as MemberOrderModel;

use think\Db;

use think\Request;

use think\Cache;

use think\Loader;

use think\Exception;

use app\mobile\model\Member as MobileMemberModel;

use app\interfaces\model\Config as ConfigModel;

use think\View;





class Member

{



    public function qrcodeWithPicture_self($invite_member_id,$type)

    {

        $level = 7;

        $size = 100;

        Loader::import('phpqrcode.phpqrcode',EXTEND_PATH);



        $url = Request::instance()->domain()."/index.php/interfaces/member/friend_reg/invite_member_id/".$invite_member_id.'/type/'.$type;



        // $url = "http://app65.app.longcai.net/index.php/mobile/user_port/login?uid=".$uid;



        //容错级别



        $errorCorrectionLevel = intval($level);



        //生成图片大小



        $matrixPointSize = intval($size);



        //生成二维码图片



        $object = new \QRcode();



        $path = ROOT_PATH . 'public/friend/'.$invite_member_id.$type.'.png';







        //第二个参数false的意思是不生成图片文件，如果你写上‘picture.png’则会在根目录下生成一个png格式的图片文件



        $res = $object->png($url, $path, $errorCorrectionLevel, $matrixPointSize, 2);

        return json(['code' => 200,'message' => 'ok','picurl' => Request::instance()->domain().'/friend/'.$invite_member_id.$type.'.png','url' => Request::instance()->domain().'/index.php/interfaces/member/friend_reg/'.'invite_member_id/'.$invite_member_id.'/type/'.$type]);

//        //准备好的logo图片

//

//        $logo = Request::instance()->domain()."/static/mobile/img_user/qrcode_logo.jpg";

//

//        //已经生成的原始二维码图

//

//        $qrcode = $path;

//

//

//

//        //logo图片存在

//

//        if ($logo !== FALSE) {

//

//            $qrcode = imagecreatefromstring(file_get_contents($qrcode));

//

//            $logo = imagecreatefromstring(file_get_contents($logo));

//

//            $qrcode_width = imagesx($qrcode);   //二维码图片宽度

//

//            $qrcode_height = imagesy($qrcode);  //二维码图片高度

//

//            $logo_width = imagesx($logo);       //logo图片宽度

//

//            $logo_height = imagesy($logo);      //logo图片高度

//

//            $logo_qr_width = $qrcode_width / 5;

//

//            $scale = $logo_width / $logo_qr_width;

//

//            $logo_qr_height = $logo_height / $scale;

//

//            $from_width = ($qrcode_width - $logo_qr_width) / 2;

//

//            //重新组合图片并调整大小[生成中间带logo的二维码  $qrcode]

//

//            imagecopyresampled($qrcode, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);

//

//

//

//        }

//

//        //2.输出二维码图片

//

//        imagepng($qrcode, $path);

//

//        //背景图片

//

//        $bgImg = ROOT_PATH . "public/static/mobile/img_user/wap_share.png";

//

//        $bgImg = imagecreatefromstring(file_get_contents($bgImg));

//

//        $bgWidth = imagesx($bgImg);       //背景图片宽度

//

//        $bgHight = imagesy($bgImg);      //背景图片高度

//

//        $code_width = imagesx($qrcode)*0.85;       //二维码图片宽度

//

//        $code_height = imagesy($qrcode)*0.85;      //二维码图片高度

//

//        $bg_from_width = ($bgWidth - $code_width) / 2;

//

//        //重新组合图片并调整大小[二维码和背景图片组合  $bgImg]

//

//        imagecopyresampled($bgImg, $qrcode, $bg_from_width*1.015, $bg_from_width*3.685, 0, 0, $code_width, $code_height, imagesx($qrcode), imagesy($qrcode));

//

//        //三合一图片

//

//        imagepng($bgImg, $path);



    }

    /*

     * 用户端 - 注册

     * @param  string $username 手机号

     * @param  string $password 密码

     * @param  string $code     验证码

     */

    public function register()

    {

        //if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        $data = Request::instance()->param();

        if (empty($data['username']) || empty($data['password']) || empty($data['code'])) throw new Exception('not Empty');

        $member_ids = db('member')->where('username',$data['username'])->value('id');

        if($member_ids) return ['code' => 400, 'message' => '此账号已注册过,请不需要重复注册'];

        //if(strlen($data['username']) != 11) return ['code' => 400, 'message' => '注册账号请填写11位手机号'];

        if($data['username'] == $data['invite_member_id'])  return ['code' => 400, 'message' => '注册账号和邀请账号不能相同'];



        if($data['invite_member_id'] === 0){

            $data['invite_member_id'] = 0;

        }elseif(strlen($data['invite_member_id']) == 11){

            $member_id = db('member')->where('username',$data['invite_member_id'])->value('id');

            if(empty($member_id))  return ['code' => 400, 'message' => '您添加的会员邀请账号不存在'];

            //·····

            $member_order = db('member_order a')->join('member b','a.member_id = b.id')->where(['b.username' => $data['invite_member_id']])->where('a.status','egt',1)->find();

            if(!$member_order) return ['code' => 400, 'message' => '此邀请码没有购买过商品,无法注册'];

            $data['invite_member_id'] = $member_id;

        }elseif (!empty($data['invite_member_id']) && strlen($data['invite_member_id']) != 11){

            $member_id = db('member')->where('id',$data['invite_member_id'])->value('id');

            if(empty($member_id))  return ['code' => 400, 'message' => '您添加的会员邀请码不存在,如果想注册第一级会员'];

        }



        // 验证

        $validate = Loader::validate('Member');

        //if (!$validate->check($data)) return ['code' => 400, 'message' => $validate->getError()];



        // 判断验证码是否正确

        $smsVerify = Cache::get('sms_verify_reg_' . $data['username']);





        if ($smsVerify != $data['code']) {

            return ['code' => 401, 'message' => '验证码错误'];

        }

        // 提交数据



        $model = new MemberModel();



        $result = $model->allowField(true)->save($data);

        if ($result) {

            try {

                (new MobileMemberModel())->distribution($data['invite_member_id'], $model->id);

                //附加会员佣金表

               // (new MobileMemberModel())->add_brokerage($model->id);

                $message_list = db('member_message')->where('type',1)->select();

                foreach ($message_list as $k => $v){

                    $insert[] = ['member_id' => $model->id ,'message_id' => $v['id'],'create_time' => time()];

                }

                db('mem_mess')->insertAll($insert);

                return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $model->id]];

            } catch (\Exception $e) {

                return ['code' => 0, $e->getMessage()];

            }

        }



        return ['code' => 403, 'message' => '网络繁忙'];





    }



    public function is_buy_goods(){

        $member_id =  Request::instance()->param('member_id');

        $con['member_id'] = ['eq',$member_id];

        $con['status'] = ['egt',1];

        $order = db('member_order')->where($con)->find();

        if($order) return ['code' => 200 , 'message' => '已经购买过商品,可以分享链接'];

        else return ['code' => 400 , 'message' => '没有购买过商品,不能分享链接'];



    }



    /*

 * 用户端 - 注册

 * @param  string $username 手机号

 * @param  string $password 密码

 * @param  string $code     验证码

 */

    public function registers()

    {

        //if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        //return ['code' => 200,'message' => 'ok'];

        // 获取参数

        $data = Request::instance()->param();

        $validate = Loader::validate('Member');

        if (!$validate->check($data)) return ['code' => 400, 'message' => $validate->getError()];

        if (empty($data['username']) || empty($data['password']) || empty($data['code'])) throw new Exception('not Empty');

        $member_ids = db('member')->where('username',$data['username'])->value('id');

        if($member_ids) return ['code' => 400, 'message' => '此账号已注册过,请不需要重复注册'];

        //if(strlen($data['username']) != 11) return ['code' => 400, 'message' => '注册账号请填写11位手机号'];

        if($data['username'] == $data['invite_member_id'])  return ['code' => 400, 'message' => '注册账号和邀请账号不能相同'];

        if($data['invite_member_id'] === 0){

            $data['invite_member_id'] = 0;

        }elseif(strlen($data['invite_member_id']) == 11){

            $member_id = db('member')->where('username',$data['invite_member_id'])->value('id');

            if(empty($member_id))  return ['code' => 400, 'message' => '您添加的会员邀请账号不存在'];

            $member_order = db('member_order a')->join('member b','a.member_id = b.id')->where(['b.username' => $data['invite_member_id']])->where('a.status','egt',1)->find();

            if(!$member_order) return ['code' => 400, 'message' => '此邀请码没有购买过商品,无法注册'];

            $data['invite_member_id'] = $member_id;

        }elseif (!empty($data['invite_member_id']) && strlen($data['invite_member_id']) != 11){

            $member_id = db('member')->where('id',$data['invite_member_id'])->value('id');

            if(empty($member_id))  return ['code' => 400, 'message' => '您添加的会员邀请码不存在,如果想注册第一级会员'];

        }



        // 验证

        

        // 判断验证码是否正确

        $smsVerify = Cache::get('sms_verify_reg_' . $data['username']);





        if ($smsVerify != $data['code']) {

            return ['code' => 401, 'message' => '验证码错误'];

        }

        // 提交数据



        $model = new MemberModel();



        $result = $model->allowField(true)->save($data);

        if ($result) {

            try {

                (new MobileMemberModel())->distribution($data['invite_member_id'], $model->id);

                //附加会员佣金表

                // (new MobileMemberModel())->add_brokerage($model->id);

                $message_list = db('member_message')->where('type',1)->select();

                foreach ($message_list as $k => $v){

                    $insert[] = ['member_id' => $model->id ,'message_id' => $v['id'],'create_time' => time()];

                }

                db('mem_mess')->insertAll($insert);

                return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $model->id]];

            } catch (\Exception $e) {

                return ['code' => 0, $e->getMessage()];

            }

        }



        return ['code' => 403, 'message' => '网络繁忙'];





    }



    public function check_bind_tel(Request $request)

    {

        if ($request->isPost()){

            //检测新绑定手机号的唯一性

            $new_bind = $request->post('tel');

            $id = (new Member())->where('username',$new_bind)->value('id');

            return !$id?['code'=>200]:['code'=>0,'message'=>'输入的手机号已存在,请更换!'];

        }

    }



    public function friend_reg(){

        $username = Request::instance()->param('invite_member_id');



        $info = db('member')->where('username',$username)->find();

        if(empty($info['nickname'])) $info['nickname'] = $info['username'];

        $view = new View();

        echo $view->fetch('',['info' => $info]);

    }



    public function choose_system()

    {

        $view = new View();

        echo $view->fetch('');

    }



    public function friend_reg_erweima(){



        //androi https://www.pgyer.com/YfKo;

        $url = '/friend.png?a='.rand(0,999);

        $view = new View();

        echo $view->fetch('',['url' => $url]);

    }





//    public function update(){

//        $username = Request::instance()->param('username',0);

//        $balance = Request::instance()->param('balance',0);

//        $integral = Request::instance()->param('integral',0);

//        $ret = Db::name('member')->where('username',$username)->update(['balance' => $balance,'integral' => $integral]);

//        $a = Db::name('member')->where('username',$username)->field('balance,integral')->find();

//        if($ret) return ['code' => 200,'balance' =>$a['balance'],'integral' =>$a['integral'] ];

//        else return ['code' => 400,'balance' =>$a['balance'],'integral' =>$a['integral'] ];

//    }



    /*

     * 用户端 - 登录

     * @param  string $username 手机号

     * @param  string $password 密码

     */

    public function login()

    {

        //if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        try {

            $username = Request::instance()->param('username');

            $password = mcs(Request::instance()->param('password'));



            if (empty($username)) throw new Exception('username not Empty');

            if (empty($password)) throw new Exception('password not Empty');



            $model = new MemberModel();

            // 验证数据

            $user_id = $model->where(['username' => $username, 'password' => $password,'status' => 1])->value('id');



            if ($user_id) {

                return ['code' => 200, 'message' => '登录成功', 'data' => ['user_id' => $user_id]];

            }



            //return ['code' => 401, 'message' => '账号或密码错误' ,'password'=>];
			return ['code' => 401, 'message' => '账号或密码错误'];
        } catch (Exception $e) {

            return ['code' => $e->getCode(), 'message' => $e->getMessage()];

        }



    }

	public function login_staff()

    {

        //if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        try {

            $username = Request::instance()->param('username');

            //$password = mcs(Request::instance()->param('password'));
			$password = Request::instance()->param('password');
			$shop_id = Request::instance()->param('shop_id');

            if (empty($username)) throw new Exception('username not Empty');

            if (empty($password)) throw new Exception('password not Empty');
			if (empty($shop_id)) throw new Exception('shop_id not Empty');


            $model = new MemberModel();
            // 验证数据
			$user_id = Db::name('shop_assignor')->where(['telephone' => $username, 'password' => $password,'shop_id' => $shop_id,'is_delete' => 1])->value('id');
			//是否删除
			$is_delete = Db::name('shop_assignor')->where(['telephone' => $username, 'password' => $password,'shop_id' => $shop_id])->value('is_delete');
			
			
            //$user_id = $model->where(['username' => $username, 'password' => $password,'status' => 1])->value('id');
			


            if ($user_id) {
				if($is_delete=='2'){
					 return ['code' => 401, 'message' => '登录失败,该会员已被删除'];	
				}
                return ['code' => 200, 'message' => '登录成功', 'data' => ['user_id' => $user_id,'shop_id' => $shop_id]];
            }
            //return ['code' => 401, 'message' => '账号或密码错误' ,'password'=>];
			return ['code' => 401, 'message' => '账号或密码错误'];
        } catch (Exception $e) {

            return ['code' => $e->getCode(), 'message' => $e->getMessage()];

        }



    }
	//////////////////////////////////////////////////////////////////////////

    public function my_team(){

        $inquire = Request::instance()->param();





        // 搜索条件





        $condition['hierarchy'] = ['like', '%,' . $inquire['member_id'] . ',%'];

        $level = Db::name('member_distribution')->where(['referrals_id' => $inquire['member_id']])->value('level');



        if (!empty($inquire['status'])) $condition['a.level'] = ['eq', $inquire['status']];



        if (!empty($inquire['title'])) $condition['b.username'] = ['like', '%' . $inquire['title'] . '%'];



//        $data = Db::view('member_distribution', 'create_time,level')

//            ->view('member', 'username phone,nickname,id', 'member.id=member_distribution.referrals_id')

//            ->where($condition)->where(['level' => $level+1])->paginate(10, false, ['query' => $inquire]);

        $data = \app\interfaces\model\MemberDistribution::alias('a')

            ->join('member b','a.referrals_id = b.id','left')

            ->field('a.create_time,a.level,b.username phone,b.nickname,b.id')

            ->where($condition)->where(['level' => $level+1])->paginate(10, false, ['query' => $inquire])->each(function($item,$key){

                $item['create_time'] = date('Y-m-d',$item['create_time']);

                if($item['nickname'] == '') $item['nickname'] = '匿名';

            });

        return ['code' => 200 ,'message' => '成功','data' => $data];

}

public function my_wallet(){

    $inquire = Request::instance()->param();

    $data = Db::name('member')->field('balance,integral,y,e,f,g,gt,is_vip')->where('id',$inquire['member_id'])->find();

    $data['total_balance'] = number_format($data['balance']+$data['integral'],2,'.','');

    return ['code' => 200 ,'message' => '成功','data' => $data];

}



    /*

     * 用户端 - 找回密码

     * @param  string $username 手机号

     * @param  string $password 密码

     */

    public function retrieve()

    {

        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        $username = Request::instance()->param('username');

        $password = mcs(Request::instance()->param('password'));



        if (empty($username) || empty($password)) throw new Exception('not Empty');



        $model = new MemberModel();



        $old_pass = $model->where('username', $username)->value('password');



        if ($old_pass == $password) return ['code' => 401, 'message' => '新旧密码不能一致'];



        // 验证数据

        $result = $model->save(['password' => $password], ['username' => $username]);



        if ($result) {

            return ['code' => 200, 'message' => '成功'];

        }



        return ['code' => 401, 'message' => '失败'];



    }



    public function get_withdraw(){

        $member_id = Request::instance()->param('member_id');

        $data['balance'] = Db::name('member')->where('id',$member_id)->value('balance');

        $data['wechat_id'] = Db::name('member')->where('id',$member_id)->value('wechat_id');

        $data['config_balance'] = db('config')->where('varname','web_lowest_withdraw')->value('varvalue');

        return ['code' => 200, 'message' => '成功','data' => $data ];

    }



    /*

 * 生成店铺订单号码

 */

    protected function make_order($shop_id)

    {

        return date('YmdHis', time())

            . mt_rand(10, 99)

            . sprintf('%010d', time() - 946656000)

            . sprintf('%03d', (float)microtime() * 1000)

            . sprintf('%03d', (int)$shop_id % 1000);



    }

    public function member_withdraw(){

        $inquire = Request::instance()->param();

        $balance = Db::name('member')->where('id',$inquire['member_id'])->value('balance');

        $web_lowest_withdraw = ConfigModel::where('varname','web_lowest_withdraw')->value('varvalue');

        $b = floor($inquire['price']/$web_lowest_withdraw);

        if($balance < $inquire['price']){

            return ['code' => 400 ,'message' => '提现金额不能大于用户余额'];

        }

        if($inquire['price'] < $web_lowest_withdraw){

            return ['code' => 400 ,'message' => '提现金额必须大于'.$web_lowest_withdraw];

        }

        $insert = [

            'member_id' => $inquire['member_id'],

            'price' => $b*$web_lowest_withdraw,

            'order_number' => $this->make_order($inquire['member_id']),

            'openid' => $inquire['opendid'],

            'create_time' => date('Y-m-d H:i:s',time()),

            'status' => 1,

            'type_id' => $inquire['type'],

            'real_name' => $inquire['real_name'],

            'name' => $inquire['name'],

        ];

        $ret = Db::name('member_withdraw')->insert($insert);



        if($ret){

            Db::name('member')->where('id',$inquire['member_id'])->setDec('balance',$b*$web_lowest_withdraw);

            return ['code' => 200 ,'message' => '提现申请中,申请提现的金额为'.$b*$web_lowest_withdraw];

        }

        return ['code' => 400 ,'message' => '提现申请失败'];



    }



    public function withdraw_list(){

        $member_id = Request::instance()->param('member_id');

        $data = (new \app\interfaces\model\MemberWithdraw())->field('id,member_id,price,create_time,status,type_id')

            ->order('create_time','desc')->where('member_id',$member_id)

            ->paginate(11)->each(function($item,$key){

                $item['create_time'] = date('Y-m-d',strtotime($item['create_time']));

                switch ($item['status'])

                {

                    case '1':

                        $item['status'] = '审核中';

                        break;

                    case '2':

                        $item['status'] = '成功';

                        break;

                    case '3':

                        $item['status'] = '失败';

                        break;

                    default:

                        $item['status'] = '无默认';

                }

                switch ($item['type_id'])

                {

                    case '1':

                        $item['type_id'] = '支付宝';

                        break;

                    case '2':

                        $item['type_id'] = '微信';

                        break;

                    case '3':

                        $item['type_id'] = '银行卡';

                        break;

                    default:

                        $item['type_id'] = '无默认';

                }

            });

        return ['code' => 200 , 'message' => '提现列表','data' => $data];

    }



    public function withdraw_view(){

        $member_id = Request::instance()->param('id');

        $data = (new \app\interfaces\model\MemberWithdraw())->field('id,member_id,price,create_time,status,order_number,type_id')

            ->order('create_time','desc')

            ->find($member_id);

        $data['create_time'] = date('Y-m-d H:i',strtotime($data['create_time']));

        switch ($data['type_id'])

        {

            case '1':

                $data['way'] = '支付宝';

                break;

            case '2':

                $data['way'] = '微信';

                break;

            case '3':

                $data['way'] = '银行卡';

                break;

            default:

                $data['way'] = '无';

        }

        switch ($data['status'])

        {

            case '1':

                $data['status'] = '审核中';

                break;

            case '2':

                $data['status'] = '成功';

                break;

            case '3':

                $data['status'] = '失败';

                break;

            default:

                $data['status'] = '无默认';

        }

        return ['code' => 200 , 'message' => '提现详情','data' => $data];

    }

    public function wechat_openid(){

        $member_id = Request::instance()->param('member_id');

        $openid = Request::instance()->param('wechat_id');

        //$wechat_id = Db::name('member')->where('id',$member_id)->value('wechat_id');

        $ret = Db::name('member')->where('id',$member_id)->update(['wechat_id' => $openid]);

        if($ret !== false){

            return ['code' => 200, 'message' => '微信授权成功'];

        }

        return ['code' => 200, 'message' => '微信授权失败',];



    }





    /*

     * 用户端 - 我的

     * @param  string $user_id 唯一标示

     */

    public function my_list()

    {

        // 获取参数

        $user_id = Request::instance()->param('user_id');



        if (empty($user_id)) throw new Exception('not Empty');



        $model = new MemberModel();



        // 验证数据

        $result = $model->where(['id' => $user_id])->field('avatar,nickname,username,is_vip')->find();







        // 待付款

        $result['wait_pay'] = (int)MemberOrderModel::where(['member_id' => $user_id, 'status' => '0'])->count();



        //已付款,待发货

        $result['wait_send_goods'] = (int)MemberOrderModel::where(['member_id' => $user_id, 'status' => '1'])->count();

        // 已发货,待收货

        $result['wait_take_goods'] = (int)MemberOrderModel::where(['member_id' => $user_id, 'status' => ['in', '2']])->count();



        // 待评价

        $result['wait_evaluate'] = (int)MemberOrderModel::where(['member_id' => $user_id, 'status' => '3'])->count();



        // 退换货

        $result['end'] = (int)MemberOrderModel::where(['member_id' => $user_id, 'status' => ['in', '4']])->count();



        $con['member_id'] = ['eq',$user_id];

        $con['status'] = ['egt',1];

        $order = db('member_order')->where($con)->find();

        if($order) $o = 1;

        else $o = 2;



        if ($result) {

            return ['code' => 200, 'message' => '成功', 'data' => $result,'is_buy' =>$o];

        }



        return ['code' => 401, 'message' => '网络繁忙','is_buy' => $o];



    }



    /*

     * 用户端 - 支付密码是否存在

     * @param  string $user_id 唯一标示

     */

    public function pay_pass()

    {

        // 获取参数

        $user_id = Request::instance()->param('user_id');



        if (empty($user_id)) throw new Exception('not Empty');



        $model = new MemberModel();



        // 验证数据

        $result = $model->where(['id' => $user_id])->value('pay_pass');



        if (!empty($result)) {

            $result = '1';

        } else {

            $result = '0';

        }



        return ['code' => 200, 'message' => '成功', 'data' => $result];



    }



    /*

     * 用户端 - 我的余额

     * @param  string $user_id 唯一标示

     */

    public function my_balance()

    {

        // 获取参数

        $user_id = Request::instance()->param('user_id');



        if (empty($user_id)) throw new Exception('not Empty');



        // 模型实例化

        $model = new MemberModel();

        $member_brokerage_model = new MemberBrokerageModel();

        $coupon_model = new MemberCouponModel();

        $red_model = new MemberPacketModel();



        //  获取数据

        $result = $model->where(['id' => $user_id])->field('balance,integral,pay_pass')->find();

        $result['actual_amount'] = $member_brokerage_model->where('member_id', $user_id)->value('actual_amount');

        $result['coupon_total'] = $coupon_model->where(['member_id' => $user_id, 'status' => 2, 'end_time' => ['egt', time()]])->count();

        $result['red_total'] = $red_model->where(['member_id' => $user_id, 'status' => 2, 'end_time' => ['egt', time()]])->count();



        if (!empty($result['pay_pass'])) {

            $result['pay_pass'] = '1';

        } else {

            $result['pay_pass'] = '0';

        }



        if ($result) {

            return ['code' => 200, 'message' => '成功', 'data' => $result];

        }



        return ['code' => 401, 'message' => '网络繁忙'];



    }



    /*

     * 用户端 - 个人信息

     * @param  string $user_id 唯一标示

     */

    public function info()

    {

        // 获取参数

        $user_id = Request::instance()->param('user_id');



        if (empty($user_id)) throw new Exception('not Empty');



        $model = new MemberModel();

        // 验证数据

        $result = $model->where(['id' => $user_id])->field('avatar,nickname,sex')->find();



        $DistributionModel = new MemberDistributionModel();

        $result['distribution_id'] = (int)$DistributionModel->where(['referrals_id' => $user_id])->value('distribution_id');



        if ($result) {

            return ['code' => 200, 'message' => '成功', 'data' => $result];

        }



        return ['code' => 401, 'message' => '网络繁忙'];



    }



    public function update_info(MemberModel $member){

        $user_id = Request::instance()->param('user_id');

        if(Request::instance()->isPost()){

            $avatar = Request::instance()->param('avatar');

            $nickname = Request::instance()->param('nickname');

            $result = $member->save(['avatar' => $avatar,'nickname' => $nickname], ['id' => $user_id]);

            if ($result !== false) {

                return ['code' => 200,'message' => '会员资料post提交user_id,avatar,nickname修改信息,修改成功'];

            }

            return ['code' => 400,'message' => '修改失败'];



        }

        $info = Db::name('member')->where('id',$user_id)->field('id,username,nickname,avatar')->find();

        return ['code' => 200,'message' => '会员资料get提交user_id获得默认查询数据','data' => $info];

    }

    public function update_info_mingming(MemberModel $member){

        $user_id = Request::instance()->param('user_id');

        if(Request::instance()->isPost()){

            $avatar = uploadImg('avatar', 'shop');

            $nickname = Request::instance()->param('nickname');

            if($avatar){$arr = ['avatar' => $avatar,'nickname' => $nickname];}else{ $arr =['nickname' => $nickname];}

            $result = $member->save($arr, ['id' => $user_id]);

            if ($result !== false) {

                return ['code' => 200,'message' => '会员资料post提交user_id,avatar,nickname修改信息,修改成功'];

            }

            return ['code' => 400,'message' => '修改失败'];



        }

        $info = Db::name('member')->where('id',$user_id)->field('id,username,nickname,avatar')->find();

        return ['code' => 200,'message' => '会员资料get提交user_id获得默认查询数据','data' => $info];

    }



    /*

     * 用户端 - 更新头像

     * @param  string $user_id 唯一标示

     */

    public function avatar_update()

    {



        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        $user_id = Request::instance()->param('user_id');

        $avatar = uploadImg('avatar', 'shop');



        if (empty($user_id) || empty($avatar)) throw new Exception('not Empty');



        $model = new MemberModel();

        // 验证数据

       // $result = $model->save(['avatar' => $avatar], ['id' => $user_id]);



        if ($avatar) {

            return ['code' => 200, 'message' => '成功', 'data' => $avatar];

        }



        return ['code' => 401, 'message' => '网络繁忙'];



    }



    /*

     * 用户端 - 更新昵称

     * @param  string $user_id 唯一标示

     */

    public function nickname_update()

    {



        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        $user_id = Request::instance()->param('user_id');

        $nickname = Request::instance()->param('nickname');



        if (empty($user_id) || empty($nickname)) throw new Exception('not Empty');





        // 启动事务

        Db::startTrans();

        try {



            // 查询是否第一次更新昵称

            $find = Db::name('integral_record')->where(['member_id' => $user_id, 'type' => '编辑昵称'])->value('id');



            // 如果是第一次

            if (empty($find)) {



                // 送积分

                Db::name('member')->where(['id' => $user_id])->setInc('integral', Cache::get('web_integral_nickname'));



                // 添加记录

                Db::name('integral_record')->insert(

                    [

                        'member_id'   => $user_id,

                        'type_id'     => '1',

                        'type'        => '编辑昵称',

                        'integral'    => Cache::get('web_integral_nickname'),

                        'title'       => '（首次）编辑昵称',

                        'create_time' => time()

                    ]

                );



            }



            Db::name('member')->where(['id' => $user_id])->update(['nickname' => $nickname]);



            // 提交事务

            Db::commit();



            return ['code' => 200, 'message' => '成功'];



        } catch (\Exception $e) {



            // 回滚事务

            Db::rollback();



            return ['code' => 401, 'message' => '网络繁忙'];

        }



    }



    /*

     * 用户端 - 性别昵称

     * @param  string $user_id 唯一标示

     */

    public function sex_update()

    {



        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        $user_id = Request::instance()->param('user_id');

        $sex = Request::instance()->param('sex');



        if (empty($user_id) || empty($sex)) throw new Exception('not Empty');



        $model = new MemberModel();



        // 验证数据

        $condition = ['sex' => $sex];



        $result = $model->allowField(true)->save($condition, ['id' => $user_id]);



        if ($result || $result == 0) {

            return ['code' => 200, 'message' => '成功', 'data' => $sex];

        }



        return ['code' => 401, 'message' => '网络繁忙'];



    }



    /*

     * 用户端 - 更新密码

     * @param  string $user_id 会员ID

     * @param  string $password 唯一标示

     * @param  string $new_pass 唯一标示

     */

    public function update_pass()

    {



        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        $user_id = Request::instance()->param('user_id');

        $password = Request::instance()->param('password', '', 'mcs');

        $new_pass = Request::instance()->param('new_pass', '', 'mcs');



        if (empty($user_id) || empty($password) || empty($new_pass)) throw new Exception('not Empty');



        $model = new MemberModel();

        if ($password == $new_pass) return ['code' => 401, 'message' => '新旧密码不能一致'];

        // 查看老密码是否正确

        $find = $model->where(['id' => $user_id, 'password' => $password])->value('id');



        if (!empty($find)) {



            //$pass = $model->where(['pay_pass' => $new_pass, 'id' => $user_id])->find();



            //if (!empty($pass)) return ['code' => 402, 'message' => '支付密码不能跟登录密码相同,请重新输入'];



            // 验证数据

            $result = Db::name('member')->where(['id' => $user_id])->update(['password' => $new_pass]);



            if ($result) {

                return ['code' => 200, 'message' => '成功'];

            }



            return ['code' => 401, 'message' => '网络繁忙'];



        }



        return ['code' => 401, 'message' => '密码错误'];



    }



    /*

     * 用户端 - 修改绑定手机号

     * @param  string $user_id      会员ID

     * @param  string $phone        手机号

     * @param  string $code         验证码

     * @param  string $new_phone    新手机号

     * @param  string $new_code     新验证码

     */

    public function update_phone()

    {



        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        $data = Request::instance()->param();



        if (empty($data['user_id']) || empty($data['phone']) || empty($data['new_phone']) || empty($data['code']) || empty($data['new_code'])) throw new Exception('not Empty');



        // 提交数据

        $model = new MemberModel();



        $phone = $model->where(['id' => $data['user_id']])->value('username');



        if ($phone <> $data['phone']) return ['code' => 402, 'message' => '输入手机号不匹配'];



        // 手机号是否存在

        $id = $model->where(['username' => $data['phone']])->value('id');



        if (empty($id)) return ['code' => 402, 'message' => '手机号不存在'];



        // 手机号是否存在

        $new_id = $model->where(['username' => $data['new_phone']])->value('id');



        if (!empty($new_id)) return ['code' => 402, 'message' => '手机号已存在'];



        // 判断验证码是否正确

        $smsVerify = Cache::get('sms_verify_find_' . $data['phone']);



        if ($smsVerify != $data['code']) {

            return ['code' => 401, 'message' => '原手机号验证码错误'];

        }



        // 判断验证码是否正确

        $new_smsVerify = Cache::get('sms_verify_reg_' . $data['new_phone']);



        if ($new_smsVerify != $data['new_code']) {

            return ['code' => 401, 'message' => '新手机号验证码错误'];

        }



        // 更新数据

        $result = $model->save(['username' => $data['new_phone']], ['username' => $data['phone']]);



        if ($result) {

            return ['code' => 200, 'message' => '成功'];

        }



        return ['code' => 401, 'message' => '网络繁忙'];



    }



    public function forget(){

        $username = Request::instance()->param('username');

        $code = Request::instance()->param('code');

        $cache_code = Cache::get('sms_verify_' . 'forget' . '_' . $username);     //

        if($code == $cache_code){

            return ['code' =>200,'message' => '验证通过'];

        }

        return ['code' =>400,'message' => '验证失败'];

    }



    /*

     * 用户端 - 新建支付密码

     * @param  string $user_id 会员ID

     * @param  string $pay_pass 支付密码

     */

    public function create_payment_code()

    {



        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        $user_id = Request::instance()->param('user_id');

        $pay_pass = Request::instance()->param('pay_pass', '', 'mcs');



        if (empty($user_id) || empty($pay_pass)) throw new Exception('not Empty');



        $model = new MemberModel();



        $find = $model->where(['password' => $pay_pass, 'id' => $user_id])->find();



        if (!empty($find)) return ['code' => 402, 'message' => '支付密码不能跟登录密码相同,请重新输入'];



        // 验证数据

        $result = Db::name('member')->where(['id' => $user_id])->update(['pay_pass' => $pay_pass]);



        if ($result || $result == 0) {

            return ['code' => 200, 'message' => '成功'];

        }



        return ['code' => 401, 'message' => '网络繁忙'];



    }



    /*

     * 用户端 - 更新支付密码

     * @param  string $user_id 会员ID

     * @param  string $pay_pass 唯一标示

     * @param  string $new_pass 唯一标示

     */

    public function update_payment_code()

    {



        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        $user_id = Request::instance()->param('user_id');

        $pay_pass = Request::instance()->param('pay_pass', '', 'mcs');

        $new_pass = Request::instance()->param('new_pass', '', 'mcs');



        if (empty($user_id) || empty($pay_pass) || empty($new_pass)) throw new Exception('not Empty');



        $model = new MemberModel();



        // 查看老密码是否正确

        $find = $model->where(['id' => $user_id, 'pay_pass' => $pay_pass])->value('id');



        if (!empty($find)) {



            $pass = $model->where(['password' => $new_pass, 'id' => $user_id])->find();



            if (!empty($pass)) return ['code' => 402, 'message' => '支付密码不能跟登录密码相同,请重新输入'];



            // 验证数据

            $result = Db::name('member')->where(['id' => $user_id])->update(['pay_pass' => $new_pass]);



            if ($result || $result == 0) {

                return ['code' => 200, 'message' => '成功'];

            }



            return ['code' => 401, 'message' => '网络繁忙'];



        }



        return ['code' => 401, 'message' => '密码错误'];



    }



    /*

     * 用户端 - 确认支付密码

     * @param  string $user_id 唯一标示

     */

    public function payment_code()

    {



        if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        // 获取参数

        $user_id = Request::instance()->param('user_id');

        $pay_pass = Request::instance()->param('pay_pass', '', 'mcs');



        if (empty($user_id) || empty($pay_pass)) throw new Exception('not Empty');



        $model = new MemberModel();





        // 获取支付密码

        $result = $model->where(['id' => $user_id])->value('pay_pass');



        // 支付密码为空

        if (empty($result)) return ['code' => 401, 'message' => '支付密码为空'];



        // 验证数据

        if ($result === $pay_pass) {

            return ['code' => 200, 'message' => '成功'];

        }



        return ['code' => 401, 'message' => '密码错误'];



    }



    /*----------------------------------------------------------------------------------------------------------------------------------------------------

     * 用户端 - 短信验证码

     * @param  string $phone    手机号

     * @param  string $type     分类

     */

    public function get_code()

    {



        //if (!Request::instance()->isPost()) return ['code' => 400, 'message' => '请求方式错误'];



        $phone = Request::instance()->param('phone');

        $type = Request::instance()->param('type');

        //Cache::set('sms_verify_' . $type . '_' . $phone, '123456', 900);     // 短信保存有效期

        //return ['code' => 200, 'message' => '发送成功', 'data' => ['code' => 123456, 'phone' => $phone]];

        $user_id = MemberModel::where(['username' => $phone])->value('id');



        if ($type == 'reg' && !empty($user_id)) {

            $find = Db::name('member')->where('username',$phone)->find();

            if(empty($find))  return ['code' => 402, 'message' => '用户未注册'];

            // 注册获取验证码

            return ['code' => 402, 'message' => '用户已注册'];



        } elseif ($type == 'find' && empty($user_id)) {

            $find = Db::name('member')->where('username',$phone)->find();

            if(empty($find))  return ['code' => 402, 'message' => '用户未注册'];

            // 找回密码获取验证码

            return ['code' => 402, 'message' => '用户未注册'];



        } elseif ($type == 'update' && empty($user_id)) {

            $find = Db::name('member')->where('username',$phone)->find();

            if(empty($find))  return ['code' => 402, 'message' => '用户未注册'];

            // 修改密码

            return ['code' => 402, 'message' => '用户未注册'];



        }elseif($type == 'forget'){

            $find = Db::name('member')->where('username',$phone)->find();

            if(empty($find))  return ['code' => 402, 'message' => '用户未注册'];

        }



        $smsVerify = Cache::get('sms_verify_' . $type . '_time_' . $phone);



        if (!empty($smsVerify)) {

            //return ['code' => 401, 'message' => '60s内只能发送一次'];

        }



        $code = rand(100000, 999999);



        $content = '您好,您的短信验证码为：' . $code;

        $result = sendSMS($phone, $code);

        if ($result) {

            Cache::set('sms_verify_' . $type . '_time_' . $phone, $code, 60); // 短信请求有效期

            Cache::set('sms_verify_' . $type . '_' . $phone, $code, 900);     // 短信保存有效期

            return ['code' => 200, 'message' => '发送成功', 'data' => ['code' => $code, 'phone' => $phone]];

        }

    }





}

